package com.lawcheukwing.MagicDroidMouse;

import java.util.Timer;
import java.util.TimerTask;

import android.R;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.widget.Toast;
import android.content.DialogInterface;

import com.varma.android.aws.webserver.WebServer;

public class HttpServer extends ProgressDialog {
	private WebServer webServer;
	private Context context;
	private WifiLock wifiLock;

	public HttpServer(Context context) {
		super(context);
		this.context = context;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		this.setProgressStyle(STYLE_SPINNER);
		this.setTitle("Embedded Web Server");
		webServer = new WebServer(context);
	}
	
	@Override
	public void onStart(){
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if(wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED){
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "MagicDroidMouse");
			wifiLock.acquire();
			int addressRaw = wifiInfo.getIpAddress();
			String addressText = String.format("%d.%d.%d.%d",
					(addressRaw & 0xff),
					(addressRaw >> 8 & 0xff),
					(addressRaw >> 16 & 0xff),
					(addressRaw >> 24 & 0xff));
			webServer.startThread();
			this.setMessage("The web server for downloading the desktop companion application is running.\n\nConnect your computer to the same network and type the following URL to download:\n\nhttp://"+addressText+":"+webServer.serverPort+"/\n\nPress Back to cancel.");
		}else{
			Toast.makeText(context, "Please enable Wi-Fi first.", Toast.LENGTH_LONG).show();
			new Timer().schedule(new TimerTask(){
				@Override
				public void run() {
					dismiss();
				}
			}, 0);
		}
	}
	
	@Override
	protected void onStop(){
		if(webServer.isAlive()) webServer.stopThread();
		if(wifiLock != null && wifiLock.isHeld()) wifiLock.release();
	}

}
